package bpay

import (
	"encoding/json"
	"errors"

	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bpay/bpay/tool"
)

type WithdrawResp struct {
	Code      string `json:"code"`
	Timestamp int64  `json:"timestamp"`
	Msg       string `json:"msg"`
	Params    string `json:"params"`
}
type PayResp struct {
	OJid        int     `json:"ojid"`
	OrderId     string  `json:"orderid"`
	Title       string  `json:"title"`
	Amount      float64 `json:"amount"`
	ApiJumpUrl  string  `json:"api_jump_url"`
	Msg         string  `json:"msg"`
	Status      int     `json:"status"`
	Account     string  `json:"account"`
	Name        string  `json:"name"`
	CreateTime  string  `json:"createtime"`
	ExpiredTime string  `json:"expiredtime"`
}

type BalanceResp struct {
	Status    int    `json:"status"`
	Timestamp int64  `json:"timestamp"`
	Msg       string `json:"msg"`
	Balance   string `json:"balance"` // 余额
	Params    string `json:"params"`
}

// 代付（提现）Withdraw
// url :请求url, mid:商户编号,orderId:商户订单号,amount: 金额保留两位小数, merchantRef: 订单号,
// bankName:银行名称 bankcardno:银行卡号,bankuser:持卡人姓名,bankbranch:IFSC,
// Notifyurl:回调地址（异步通知地址）,SecretKey:密钥
func Withdraw(url, mid, orderId, amount, merchantRef, bankName, bankCardNo, bankUser, bankBranch, NotifyUrl, SecretKey string) (resp WithdrawResp, err error) {
	// 请求第三方接口
	params := make(map[string]any)
	params["orderid"] = orderId
	params["mid"] = mid
	params["amount"] = amount
	params["title"] = merchantRef
	params["bankname"] = bankName
	params["bankcardno"] = bankCardNo
	params["bankuser"] = bankUser
	params["bankbranch"] = bankBranch
	params["Notifyurl"] = NotifyUrl
	if v, err := tool.GenerateSignature(amount, bankCardNo, mid, orderId, SecretKey); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign"] = v
	}
	output, err := tool.SendPostFormUrlEncoded(url, params)

	if err != nil {
		return resp, err
	}
	var result WithdrawResp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.Code != "1" {
		return resp, errors.New(result.Msg)
	}
	return result, nil
}

// 商户余额查询 Balance
// url :请求url, mid:商户编号
func Balance(url, mid string) (resp BalanceResp, err error) {
	// 请求第三方接口
	params := make(map[string]any)
	params["mid"] = mid
	output, err := tool.SendPostFormUrlEncoded(url, params)

	if err != nil {
		return resp, err
	}
	var result BalanceResp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.Status != 1 {
		return resp, errors.New(result.Msg)
	}
	return result, nil
}

// 代收（充值） bPay
// url :请求url, mid:商户编号,orderId:商户订单号,currency:货币，amount: 金额保留两位小数,
// paytype：支付类型，IP:用户IP,notifyurl: 异步通知URL,returnurl: 同步跳转URL,
// version:版本号 note:订单备注说明,SecretKey:密钥
func BPay(url, mid, orderId, amount, payType, IP, notifyUrl, returnUrl, version, note, SecretKey string) (resp PayResp, err error) {
	// 请求第三方接口
	params := make(map[string]any)
	params["orderid"] = orderId
	params["mid"] = mid
	params["amount"] = amount
	params["paytype"] = payType
	params["IP"] = IP
	params["notifyurl"] = notifyUrl
	params["returnurl"] = returnUrl
	params["version"] = version
	params["note"] = note
	if v, err := tool.GenerateSignatureByPay(mid, orderId, amount, note, payType, notifyUrl, returnUrl, SecretKey); err != nil {
		return resp, errors.New("ErrSignGenerateFailed")
	} else {
		params["sign"] = v
	}
	output, err := tool.SendPostFormUrlEncoded(url, params)

	if err != nil {
		return resp, err
	}
	var result PayResp
	err = json.Unmarshal([]byte(output), &result)
	if err != nil {
		return resp, err
	}
	if result.Status != 1 {
		return resp, errors.New(result.Msg)
	}
	return result, nil
}
